package sg.edu.nus.iss.cats.action;

import javax.servlet.http.*;
import java.util.*;
import org.apache.struts.action.*;

import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.controller.*;
import sg.edu.nus.iss.cats.dataaccess.*;

public class ApprovalViewAction extends Action {

 
	public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
                                    
        ActionErrors errors = new ActionErrors();
        HttpSession session = request.getSession();

        try {
            System.out.println("In ApprovalViewAction");

            //Get employee from UserSession
            UserSession userSession =
                (UserSession) session.getAttribute("USERSESSION");
            Employee manager = userSession.getEmployee();
            System.out.println("ApprovalViewAction " + manager.getEmployeeId());

            CourseDAO courseDAO = DAOFactory.getInstance().getCourseDAO();
            Vector v = new Vector();
            Employee[] subordinates = userSession.getSubordinates();
            for (int i = 0; i < subordinates.length; i++) {
                Employee sub = subordinates[i];
                Course[] courses =
                    courseDAO.findCoursesPendingByEmployee(sub.getEmployeeId());
                    
                Vector courseVec = new Vector();
                for (int j=0;j<courses.length;j++){
                
                    courseVec.add(courses[j]);
                }
                if (courses.length > 0) {
                    EmployeeCourses courseList = new EmployeeCourses();
                    courseList.setEmployee(sub);
                    courseList.setCourses(courseVec);
                    v.add(courseList);
                }
            }
            EmployeeCourses[] result = new EmployeeCourses[v.size()];
            result = (EmployeeCourses[]) v.toArray(result);
            request.setAttribute("employeeCourseLists", result);

            return mapping.findForward("success");

        } catch (Exception e) {
            //return an ActionForward respresenting the logical failure page
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError("error.employee.notfound"));
            // Report any errors we have discovered back to the original form
            saveErrors(request, errors);
            servlet.log(
                "EmployeeHistoryAction: Employee could not be found in session ",
                0);
            return mapping.findForward("error");
        }
    }
}